package top.lucas9.wechat.push.util;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import top.lucas9.wechat.push.entity.Weather;
import top.lucas9.wechat.push.entity.WeatherDayResult;

import java.util.Objects;

/**
 * @author lucas9
 * @date 2022/11/29 21:26
 */
@Slf4j
public class WeatherUtil {

    private static final String DEFAULT_LANG = "zh";

    public static Weather getWeather(String latitude, String longitude) {
        String requestUrl = buildRequestUrl(latitude, longitude, null);
        String response = HttpUtil.get(requestUrl);
        WeatherDayResult weatherDayResult = JSONUtil.toBean(response, WeatherDayResult.class);
        Assert.isTrue(Objects.equals(weatherDayResult.getCode(), WeatherDayResult.SUCCESS_CODE), "获取天气失败");
        WeatherDayResult.Daily todayWeather = weatherDayResult.getTodayWeather();
        Weather weather = new Weather();
        BeanUtils.copyProperties(todayWeather, weather);
        return weather;
    }

    /**
     * 构建请求地址
     *
     * @param latitude  纬度
     * @param longitude 经度
     * @param lang      语言，默认中文
     * @return
     */
    private static String buildRequestUrl(String latitude, String longitude, @Nullable String lang) {
        if (!StringUtils.hasLength(lang)) {
            lang = DEFAULT_LANG;
        }
        return String.format("%s?location=%s,%s&key=%s&lang=%s", cityRequestUrl, latitude, longitude, key, lang);
    }

    public void setKey(String key) {
        WeatherUtil.key = key;
    }

    public void setCityRequestUrl(String cityRequestUrl) {
        WeatherUtil.cityRequestUrl = cityRequestUrl;
    }

    public void setGridRequestUrl(String gridRequestUrl) {
        WeatherUtil.gridRequestUrl = gridRequestUrl;
    }
}
